﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.SearchStatistics.Month
{
    public partial class MonthCompareStatistics : Page
    {
        private StatisticsReportViewModel m_ViewModel;

        public MonthCompareStatistics()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MonthCompareStatistics_Loaded);
        }

        private void MonthCompareStatistics_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            cmbYear.ItemsSource = FayshineManager.Instance.GetYearSource();
            cmbYear.SelectedValue = DateTime.Now.Year;

            cmbMonth.ItemsSource = FayshineManager.Instance.GetMonthSource();
            cmbMonth.SelectedValue = DateTime.Now.Month;

            m_ViewModel = new StatisticsReportViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                DateTime time = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);
                List<HistoryPassengerFlow> sourcePassengers = new List<HistoryPassengerFlow>();

                HistoryPassengerFlow thisMonth = new HistoryPassengerFlow();
                thisMonth.DisplayTitle = "本月";
                thisMonth.InCount = firstHistoryPassengerFlow.Where(t => t.HistoryTime.Month == time.Month).First().InCount;
                thisMonth.OutCount = firstHistoryPassengerFlow.Where(t => t.HistoryTime.Month == time.Month).First().OutCount;
                sourcePassengers.Add(thisMonth);

                HistoryPassengerFlow lastMonth = new HistoryPassengerFlow();
                lastMonth.DisplayTitle = "上月";
                if (time.Month == 1)
                {
                    lastMonth.InCount = secondHistoryPassengerFlow.Where(t => t.HistoryTime.Month == 12).First().InCount;
                    lastMonth.OutCount = secondHistoryPassengerFlow.Where(t => t.HistoryTime.Month == 12).First().OutCount;
                }
                else
                {
                    lastMonth.InCount = firstHistoryPassengerFlow.Where(t => t.HistoryTime.Month == time.Month - 1).First().InCount;
                    lastMonth.OutCount = firstHistoryPassengerFlow.Where(t => t.HistoryTime.Month == time.Month - 1).First().OutCount;
                }
                sourcePassengers.Add(lastMonth);

                HistoryPassengerFlow lastYearMonth = new HistoryPassengerFlow();
                lastYearMonth.DisplayTitle = "去年同期";
                lastYearMonth.InCount = secondHistoryPassengerFlow.Where(t => t.HistoryTime.Month == time.Month).First().InCount;
                lastYearMonth.OutCount = secondHistoryPassengerFlow.Where(t => t.HistoryTime.Month == time.Month).First().OutCount;
                sourcePassengers.Add(lastYearMonth);

                HistoryPassengerFlow thisYearAve = new HistoryPassengerFlow();
                thisYearAve.DisplayTitle = "今年平均";
                thisYearAve.InCount = Convert.ToInt32(firstHistoryPassengerFlow.Average(t => t.InCount));
                thisYearAve.OutCount = Convert.ToInt32(firstHistoryPassengerFlow.Average(t => t.OutCount));
                sourcePassengers.Add(thisYearAve);

                HistoryPassengerFlow lastYearAve = new HistoryPassengerFlow();
                lastYearAve.DisplayTitle = "去年平均";
                lastYearAve.InCount = Convert.ToInt32(secondHistoryPassengerFlow.Average(t => t.InCount));
                lastYearAve.OutCount = Convert.ToInt32(secondHistoryPassengerFlow.Average(t => t.OutCount));
                sourcePassengers.Add(lastYearAve);

                Title vcChart1Title = new Visifire.Charts.Title();
                vcChart1Title.Text = time.Year + "年" + time.Month + "月" + GetChartSubTitle() + "同期客流对比";
                vcChart1.Titles.Add(vcChart1Title);

                DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "进", ChartValueTypes.Auto);
                series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
                series.DataSource = sourcePassengers;
                vcChart1.Series.Add(series);

                DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Column, "出", ChartValueTypes.Auto);
                series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
                series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
                series2.DataSource = sourcePassengers;
                vcChart1.Series.Add(series2);

                this.dataGrid.ItemsSource = sourcePassengers;

            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                }
            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                    if (selectedArea.Count > 1)
                    {
                        this.cmbPassenger.IsEnabled = false;
                    }
                    else
                    {
                        this.cmbPassenger.IsEnabled = true;
                    }

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
                cmbPassenger_DropDownClosed(null, null);
            }
        }

        private void cmbPassenger_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                var selectMonitorAreaExts = m_ViewModel.MonitorAreaGateExts.Where(a => a.IsSelected).ToList();

                if (selectMonitorAreaExts.Count > 0)
                {
                    cbItemDisplay2.Content = selectMonitorAreaExts.Count > 1 ? selectMonitorAreaExts[0].Name + "..." : selectMonitorAreaExts[0].Name;

                }
                else
                {
                    cbItemDisplay2.Content = string.Empty;
                }
                cmbPassenger.SelectedItem = null;
                cmbPassenger.SelectedItem = cbItemDisplay2;
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime dateTime = new DateTime((int)cmbYear.SelectedValue, (int)cmbMonth.SelectedValue, 1);

                m_ViewModel.RefreshMonthCompareReport(true, dateTime);
            }
        }

        private string GetChartSubTitle()
        {
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name;
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            return title1;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }


    }
}
